/**
 * 
 */
package jfengao.oauth.client;

import java.util.Base64;

/**
 * @author gaofeng
 * @date 2018年9月17日
 */
public class OauthClient {

	private SimpleNetworkExecutor networkExecutor;
	private OauthInfo oauthinfo;
	
	protected OauthClient(String grantType) {
		oauthinfo = new OauthInfo(grantType);
		networkExecutor = new SimpleNetworkExecutor();
	}
	
	/**
	 * 
	 * @param grantType of GrantTypes
	 * @return OauthClient
	 */
	public static OauthClient builderClient(String grantType) {
		OauthClient oauthClient = new OauthClient(grantType);
		return oauthClient;
	}
	
	public OauthClient addHeader(String key,String val) {
		this.networkExecutor.addHeader(key, val);
		return this;
	}
	public OauthClient addParam(String key,String val) {
		this.networkExecutor.addParam(key, val);
		return this;
	}
	
	public OauthClient setTarget(String server) {
		oauthinfo.setServer(server);
		return this;
	}
	
	/**
	 * 客户凭证
	 * @param clientId
	 * @param passwd which is secret
	 */
	public OauthClient setClientInfo(String clientId,String clientSecret) {
		this.oauthinfo.setClientId(clientId);
		this.oauthinfo.setClientSecret(clientSecret);
		return this;
	}
	
	/**
	 * 密码模式下使用
	 * @param username
	 * @param passwd
	 * @return
	 */
	public OauthClient setAccount(String username,String passwd) {
		oauthinfo.setUsername(username);
		oauthinfo.setPasswd(passwd);
		return this;
	}
	
	public OauthClient redirectUri(String uri) {
		oauthinfo.setRedirectUrl(uri); 
		return this;
	}
	
	public OauthClient authCode(String code) {
		oauthinfo.setCode(code);
		return this;
	}
	
	public OauthClient scopes(String scopes) {
		oauthinfo.setScope(scopes);
		return this;
	}
	
	public OauthInfo getOauthinfo() {
		return oauthinfo;
	}

	public void setOauthinfo(OauthInfo oauthinfo) {
		this.oauthinfo = oauthinfo;
	}
	
	public String execute() {
		prepare();
		return networkExecutor.execute(this);
	}

	private void prepare() {
		
	}
	
	public static void main(String[] args) {
		new Thread() {
			public void run() {
				//同步请求,需要自己放到线程中
				String response = OauthClient.builderClient("authorization_code")
				      .setTarget("http://127.0.0.1:8080/oauth/token") //服务器地址  http://127.0.0.1:8080/oauth/authorize  http://127.0.0.1:8080/oauth/token
				      .setClientInfo("client2018", "123123") //客户端信息
				      .setAccount("admin", "admin")
				      .scopes("write")
				      .authCode("nGKFmX") //授权码模式code
				      .redirectUri("http://127.0.0.1:8080/callback")
				   //   .addParam("sk","333") //添加额外请求参数
				   //  .addHeader("myhead","43334")  //添加额外请求头
				   //   .redirectUri("http://www.baidu.com/") //简化模式需要回调url
				      .execute();
				System.err.println(response);
			};
		}.start();
	}
}
